<template>
  <div class="app-container">
    <div ref="list" class="list_container" @scroll="scrollEvent">
      <div class="list_scroll" :style="{ height: listHeight + 'px' }"></div>
      <div
        class="list"
        :style="{ transform: `translateY(${this.startOffset}px)` }"
      >
        <div class="list_item" v-for="item in visibleData" :key="item" :style="{height:itemHeight+'px'}">
          {{ item }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      listData: [], //总数据
      //每项高度
      itemHeight: 50,
      //可视区域高度
      screenHeight: 0,
      //偏移量
      startOffset: 0,
      //起始索引
      start: 0,
      //结束索引
      end: 0,
    };
  },
  computed: {
    //列表总高度
    listHeight() {
      return this.listData.length * this.itemHeight;
    },
    //可显示的列表项数
    //+2是为了多渲染两个节点，尽量减少快速滑动的时候白屏的影响
    visibleCount() {
      return Math.ceil(this.screenHeight / this.itemHeight) + 2;
    },
    //获取真实显示列表数据
    visibleData() {
      return this.listData.slice(
        this.start,
        Math.min(this.end, this.listData.length)
      );
    },
  },
  created() {
    this.onPullDownRefresh();
  },
  mounted() {
    this.screenHeight = this.$refs.list.clientHeight;
    this.start = 0;
    this.end = this.start + this.visibleCount;
  },
  methods: {
    // 滚动事件
    scrollEvent() {
      //当前滚动位置
      let scrollTop = this.$refs.list.scrollTop;
      if (this.screenHeight + scrollTop == this.listHeight) {
       
        this.onReachBottom(); //触底加载
      } else if (scrollTop == 0) {
        
        this.onPullDownRefresh();//触顶刷新
      }

      //防止多次计算 只有在需要变化时再计算
      if (this.start != Math.floor(scrollTop / this.itemHeight)) {
        this.start = Math.floor(scrollTop / this.itemHeight);
        this.end = this.start + this.visibleCount;
        this.startOffset = scrollTop - (scrollTop % this.itemHeight);
      }
    },

    //下拉刷新（演示demo代码，实际应该是请求分页接口获取数据）
    onPullDownRefresh() {
      let d = [];
      for (let i = 1; i <= 10; i++) {
        d.push(i);
      }
      this.listData = d;
    },
    
    //上拉加载（演示demo代码，实际应该是请求分页接口获取数据）
    onReachBottom() {
      let d = [];
      let k = this.listData.length;
      for (let i = k + 1; i <= 10 + k; i++) {
        d.push(i);
      }
      this.listData = this.listData.concat(d);
    },
  },
};
</script>


<style scoped>
.list_container {
  margin: 20px 30px 0;
  height: 500px;
  overflow: auto;
  border: 1px solid;
  position: relative;
  -webkit-overflow-scrolling: touch;
}

.list_scroll {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  z-index: -1;
}

.list {
  left: 0;
  right: 0;
  top: 0;
  position: absolute;
  text-align: center;
}

.list_item {
  color: #333;

  box-sizing: border-box;
  border-bottom: 1px solid #999;
}
</style>
